<?php

require "conf.php";
require_once "data/dao/BaseDAO.php";
require_once "application/user/UserUtils.php";
require_once "application/WishListUtils.php";

class WishListDAO extends BaseDAO{
	
	
	/**
	 * gets the users collection of games from the database
	 * 
	 * @param $id
	 * @return Collection
	 */
	public function getWishList($userId){
		
		if(!UserUtils::idMatchesLoggedInUser($userId))
			throw new Exception("attempting to retrive a wish list that is not owned" .
					" by the logged in user!");		
	
		if(!UserUtils::userExists($userId))
			throw new Exception("attempting to query wish list table for a user that" .
					" does not exist!");

		self::connect();
		$find = mysql_query("SELECT * FROM " . WISH_LIST_TABLE . " WHERE user_id = '$userId'");
		
		if(mysql_num_rows($find) == 0)
			return null;
					
		while($row = mysql_fetch_assoc($find)){
			$games = explode(",", $row['game_list']);
			return $games;
		}
	}
	
	public function updateWishList($games, $userId){
		
		if(!UserUtils::idMatchesLoggedInUser($userId))
			throw new Exception("attempting to update a wish list that is not owned" .
					" by the logged in user!");		

		if(!is_string($games))
			throw new Exception("attempting to insert a non string value into table!");
			
		self::connect();
		
		// if user does not already have a collection, create one
		if(!WishListUtils::userHasAWishList($userId)){
			$result = mysql_query("INSERT INTO " . WISH_LIST_TABLE .
						" (user_id, game_list) VALUES('$userId', '$games')");
			return;
		}
				
		$result = mysql_query("UPDATE " . WISH_LIST_TABLE . 
					" SET game_list = '$games' " .
					"WHERE user_id = '$userId'");
		
		if(WishListUtils::wishListIsEmpty($userId))
			$this->deleteWishList($userId);
					
		if(!$result)
			throw new Exception("sql query failed when updating collection table");
	}
	
	public function deleteWishList($userId){
		
		self::connect();
		mysql_query("DELETE FROM " . WISH_LIST_TABLE . " WHERE user_id = '$userId'");
	}

	public function getNumberOfWishListsContainingGame($id){
		
		self::connect();
		$find = mysql_query("SELECT * FROM " . WISH_LIST_TABLE . " WHERE " .
				"game_list like '%$id%'");
				
		return mysql_num_rows($find);
	}
	
	public function getWishListCount($gameId){
		
		self::connect();
		$find = mysql_query("SELECT COUNT(*) FROM " . WISH_LIST_TABLE . " WHERE " .
				"game_list like '%$gameId%'");
		
		while($row = mysql_fetch_array($find)){
			return $row[0];
		}
	}
}
?>
